<template>
  <div>
    <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
      <div class="ledgerTitle">项目信息</div>
      <el-form-item label-width="100px" label="项目名称:" prop="projectName">
        {{form.projectName}}
      </el-form-item>
      <div class="ledgerTitle">审核说明</div>
      <el-row>
        <el-col>
          <el-form-item label-width="100px" label="附件：">
            <el-upload
              class="upload-demo"
              action="/admin/sys-file/upload"
              :headers="{Authorization}"
              :file-list="fileList"
              :on-preview="handlePreview"
              :show-file-list="true">
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="ledgerTitle">审核对比分析表初稿</div>
      <el-row>
        <el-col>
          <el-table
            ref="table"
            :data="tableData"
            :model="tableData"
            style="width: 70%;margin: auto"
            max-height="450"
            highlight-current-row
          >
            <el-table-column label="序号" width="100">
              <template #default="{ $index }">
                <span>{{ $index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="名称">
              <template #default="{ row }">
                <pre class="pre-style">{{ row.name }}</pre>
              </template>
            </el-table-column>
            <el-table-column label="是否对比表" width="200" align="center">
              <template #default="{ row }">
                <template>
                  <el-radio-group v-model="row.compare">
                    <el-radio border style="margin: 0 5px 0 5px" :label="1">是</el-radio>
                    <el-radio border style="margin: 0 5px 0 5px" :label="0">否</el-radio>
                  </el-radio-group>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="附件" width="280">
              <template #default="{ row, $index }">
                <el-upload
                  class="upload-demo"
                  action="/admin/sys-file/upload"
                  :headers="{Authorization}"
                  :on-preview="handlePreview"
                  :show-file-list="true"
                  :file-list="row.fileList">
                </el-upload>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>

import {getReport} from "@/api/adis/report/reportOpinion";
import {mapGetters} from "vuex";

export default {
  name: 'AuditEngineeringReportDraftView',
  props: {
    id: {
      type: String,
      default: ''
    },
    params: {
      type: Object,
    },
  },
  components: {},
  dictTypes: ['audit_type'],
  computed:{
    ...mapGetters(["permissions"])
  },
  data() {
    return {
      isView:false,
      isAdvice:true,
      isReport:false,
      adviceForm:{
        auditStatus:'',
        createDate : `${new Date().getFullYear()}年${new Date().getMonth() + 1}月${new Date().getDate()}日`
      },
      form: {},
      tableData:[],
      formDisplay:false,
      auditView: 'ReportAuditTypeAuditView1',
      fileList:[],
      Authorization: ''
    }
  },
  created() {
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          getReport(this.id).then((res)=>{
            if (res.data.data !== null){
              this.handleDraftResponse(res.data.data)
              this.$emit('data-loaded', true);
            } else {
              this.$emit('data-loaded', false);
            }
          }).catch(() => {
            this.$emit('data-loaded', false);
          })
        }
      },deep: true, immediate: true
    },
    params: {
      handler(val) {
        if (val) {
          this.handleDraftResponse(val)
        }
      },deep: true, immediate: true
    },
  },
  methods: {
    handleDraftResponse(val){
      this.form = val;
      this.fileList = this.form.attachments;
      this.fileList.forEach((item) =>{
        item.name = item.fileName;
        item.url = item.fileUrl;
      })
      this.tableData = this.form.projectReportAttachments || []
      this.tableData.forEach(item => {
        item.fileList = []
        item.attachments.forEach(col => {
          item.fileList.push({name: col.fileName, url: col.fileUrl})
        })
      })
    },
    /**表格处理*/
    onAddItem(val) {
      // 在这里添加添加新项目的逻辑
      if (!this.tableData) this.tableData = []
      this.tableData.push({
        attachmentType: val.attachmentType || '',
        templateId: this.tableData.length + 1,
        name: val.name || '',
        accept: val.accept || '',
        remark: val.remark || '',
      })
    },
    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        });
        this.selectedRows = [];
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = [];
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },

    viewReport(){
      this.isAdvice=true;
      this.isReport=false;
      // getReport(this.id).then((res)=>{
      //   console.log(res);
      //   this.form = res.data.data;
      //   this.form.employmentDates=[this.form.employmentStartDate,this.form.employmentEndDate];
      // })
    },
    viewAdvice(){
      this.isAdvice=false;
      this.isReport=true;
      this.adviceForm.auditedCompanyName = this.form.auditedCompanyName;
      this.adviceForm.projectName = this.form.projectName;
      getByReportId(this.id).then((res)=>{
        if (res.data.data != null){
          console.log(res,12356);
          this.adviceForm = res.data.data;
          this.adviceForm.createDate = `${new Date().getFullYear()}年${new Date().getMonth() + 1}月${new Date().getDate()}日`;
        }
      })
    },
    submitOpinion(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.employmentStartDate = this.form.employmentDates[0];
          this.form.employmentEndDate = this.form.employmentDates[1];
          console.log(this.form);
          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(item.suggestion === ''){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行整改措施不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return
          this.form.projectReportProblems = []
          this.tableData.forEach((item) => {
            this.form.projectReportProblems.push(item);
          })

          this.loading = true;
          submitOpinion(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitAdvice(){
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          // this.adviceForm.reportId = this.form.reportId;
          this.adviceForm.projectId = this.form.projectId;
          this.loading = true;
          submitAdvice(this.adviceForm).then((res) => {
            this.adviceForm.adviceId = res.data.data;
            console.log(this.adviceForm);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    openWord() {
      if(!this.form.wordFile) {
        this.$message({
          type: "warning",
          message: "该项尚未上传相关文书!"
        });
        return;
      }
      // this.$router.push({path:'/webOffice', query: {url: this.form.wordFile}})
      const { href } = this.$router.resolve({
        path: '/webOffice',
        query: {
          url: this.form.wordFile,
          type: this.isAudit ? 'edit' : 'view',
        }
      });
      window.open(href, '_blank');
    },
    handleSuccess(response, file, fileList){
      console.info(response);
      if (!this.fileList) {
        this.fileList = [{url: response.data.url, name: response.data.fileName}]
      } else {
        this.fileList.push({url: response.data.url, name: response.data.fileName})
      }
    },
    handlePreview(file) {
      const a = document.createElement('a');
      let url = file.url ? file.url : file.response.data.url;
      console.log(url);      // let fileName = '你想要的文件名.docx'; // 这里设置你想要的文件名，包括扩展名
      a.setAttribute('download', file.name);
      a.setAttribute('href', url);
      a.click();
    },
  }
}
</script>

